package com.jacobson.huobi.mvp.fragment

import android.app.Dialog
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Intent
import android.content.Intent.getIntent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Bundle
import android.provider.MediaStore
import android.view.*
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.graphics.scaleMatrix
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.fastjson.JSONObject
import com.bumptech.glide.Glide
import com.jacobson.core.base.FragmentImmersive
import com.jacobson.core.di.components.AppComponent
import com.jacobson.core.di.modules.ActivityModule
import com.jacobson.core.widget.adapter.ListRecyclerAdapter
import com.jacobson.huobi.Constants
import com.jacobson.huobi.R
import com.jacobson.huobi.common.BaseSelectableFragment
import com.jacobson.huobi.common.constants.CommonConstant
import com.jacobson.huobi.custom.dialogs.RechargeDialog
import com.jacobson.huobi.di.components.DaggerVipFragmentComponent
import com.jacobson.huobi.di.modules.VipFragmentModule
import com.jacobson.huobi.entities.VipRechargeCostInfo
import com.jacobson.huobi.entities.VipRechargeInfo
import com.jacobson.huobi.entities.events.VipRechargeEvent
import com.jacobson.huobi.entities.evt.VipRechargeSubmitEvt
import com.jacobson.huobi.entities.response.CommonResponse
import com.jacobson.huobi.entities.response.VipRechargeResponse
import com.jacobson.huobi.mvp.adapters.VipReChargeAdapter
import com.jacobson.huobi.mvp.contract.VipContract
import com.jacobson.huobi.utils.StringUtil
import kotlinx.android.synthetic.main.dialog_recharge.*
import kotlinx.android.synthetic.main.fragment_vip.*
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import org.simple.eventbus.EventBus
import org.simple.eventbus.Subscriber
import java.io.File
import java.io.FileOutputStream
import java.util.jar.Attributes
import javax.inject.Inject

@Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")
@FragmentImmersive
class VipFragment : BaseSelectableFragment<VipContract.Presenter>(),
    VipContract.View {

    private var hadInjected = false

    private var isSelected = false

    private var selVipRechargeInfo: VipRechargeInfo? = null //当前选择的充值方式

    private var rechargeDialog: RechargeDialog? = null //对话框对象


    private var vipUploadKey = "" //上传图片后保存的key

    private var selVipLevel = 4 //默认初级会员

    @field:Inject
    lateinit var vipReChargeAdapter: VipReChargeAdapter


    override fun setupFragmentComponent(appComponent: AppComponent) {
        DaggerVipFragmentComponent.builder()
            .appComponent(appComponent)
            .vipFragmentModule(VipFragmentModule(this))
            .activityModule(ActivityModule(activity!!))
            .build()
            .inject(this)
        hadInjected = true
    }

    override fun initView(savedInstanceState: Bundle?): Int = R.layout.fragment_vip
    override fun initData(savedInstanceState: Bundle?) {
        logger.d("SymbolFragment >>> $vipReChargeAdapter")
        initItem()
        initBtn()

        vipReChargeAdapter.setOnItemClickListener(object :
            ListRecyclerAdapter.OnItemClickListener<VipRechargeInfo> {
            override fun onItemClick(
                dataList: List<VipRechargeInfo>,
                data: VipRechargeInfo,
                position: Int
            ) {
                vipReChargeAdapter.setExpandPosition(position)
                presenter.loadRechargeCost(data.id)
                selVipRechargeInfo = data
            }
        })
        with(vipRecyclerView) {
            layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(com.jacobson.huobi.components.SpaceItemDecoration(3f))
            adapter = vipReChargeAdapter
        }
        EventBus.getDefault().post(VipRechargeEvent(true, 4))

    }

    @Subscriber
    private fun onUpdate(vipRechargeEvent: VipRechargeEvent) {
//        vipLevel = this.activity!!.intent.getIntExtra(VIP_TAB_SEL_KEY, 4)
        if (vipRechargeEvent.isRefresh) {
            selVipLevel = vipRechargeEvent.vipLevel
            presenter.loadRechargeSupportList(vipRechargeEvent.vipLevel)
        }
    }

    /**
     * 初始化组件
     */
    private fun initItem() {
        tvVipChargeUrl.hint = Constants.CHARGE_URL
    }

    /**
     * 初始化按钮点击事件
     */
    private fun initBtn() {
//        ivVipRecharge.setOnClickListener {
//            openSysGallery()
//        }

        btnCopyChargeUrl.setOnClickListener {
            var clipboardManager =
                this.context!!.getSystemService(AppCompatActivity.CLIPBOARD_SERVICE) as ClipboardManager
            var clip = ClipData.newPlainText("text", Constants.CHARGE_URL)
            clipboardManager.primaryClip = clip
            Toast.makeText(this.context, "交易地址复制成功", Toast.LENGTH_SHORT).show()
        }

        btnOpenRecharge.setOnClickListener {
            this.rechargeOpen()
        }

        btnCopyChargeImage.setOnClickListener {
            openBigImg()
        }
    }

    /**
     * 打开大图
     */
    private fun openBigImg() {
        var imgDialog = Dialog(this.context)
        var imgLayout = getImgLL()
        imgDialog.setContentView(imgLayout)
//        var attr = WindowManager.LayoutParams()
//        attr.width = WindowManager.LayoutParams.MATCH_PARENT
//        attr.height = WindowManager.LayoutParams.MATCH_PARENT
//        imgDialog.window.attributes = attr
        imgDialog.window.decorView.setPadding(0, 0, 0, 0)
        imgDialog.window.decorView.setBackgroundColor(Color.TRANSPARENT)
        imgDialog.show()
        imgDialog.setCanceledOnTouchOutside(true)
        imgLayout.setOnClickListener {
            imgDialog.dismiss()
        }
    }

    private fun getImgLL():  LinearLayout{
        var ll = LinearLayout(this.context)
        ll.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
        ll.gravity = Gravity.CENTER
        ll.setHorizontalGravity(Gravity.CENTER)
        ll.setVerticalGravity(Gravity.CENTER)
        var img = ImageView(ll.context)
        img.setBackgroundResource(R.drawable.address)

        img.layoutParams = ViewGroup.LayoutParams(700, 700)

        ll.addView(img)
        return ll
    }
    /**
     * 打开充值申请
     */
    private fun rechargeOpen() {
        if (selVipRechargeInfo == null || selVipLevel != selVipRechargeInfo!!.vipLevel) {
            Toast.makeText(this.context, "请先选择充值方式", Toast.LENGTH_SHORT).show()
            return
        }
        var rechargeSupportId: String = selVipRechargeInfo!!.id.toString()
//        var transactionId = etTransactionId.text.toString()
//        var num = etNum.text.toString()
//        var originAddress = ""
//        var screenshotKey = vipUploadKey
//
        if (rechargeSupportId.isNullOrEmpty()) {
            Toast.makeText(this.context, "请先选择充值方式", Toast.LENGTH_SHORT).show()
            return
        }
//        if (transactionId.isNullOrEmpty()) {
//            Toast.makeText(this.context, "交易ID不能为空", Toast.LENGTH_SHORT).show()
//            return
//        }
//        if (num.isNullOrEmpty()) {
//            Toast.makeText(this.context, "交易数量不能为空", Toast.LENGTH_SHORT).show()
//            return
//        }
//        if (screenshotKey.isNullOrEmpty()) {
//            Toast.makeText(this.context, "转账记录截图不能为空", Toast.LENGTH_SHORT).show()
//            return
//        }
//        num.toDouble()
//        presenter.rechargeSubmit(VipRechargeSubmitEvt(recharge_support_id = rechargeSupportId, transaction_id = transactionId,
//            num = num.toDouble(),origin_address = originAddress,screenshot_key = screenshotKey))
        rechargeDialog = this.context?.let {
            RechargeDialog(
                it,
                VipRechargeSubmitEvt(recharge_support_id = rechargeSupportId)
            )
        }
        rechargeDialog!!.show()
        rechargeDialog!!.setOnclickListener(object : View.OnClickListener {
            override fun onClick(v: View) {
                if (v.id == R.id.btnSubMitRecharge) {
                    var evt = rechargeDialog!!.getDialogSubmitEvt()
                    evt.screenshot_key = vipUploadKey
                    submitRecharge(evt)
                }
                if (v.id == R.id.ivVipRecharge) {
                    openSysGallery()
                }
            }
        })

    }

    /**
     * 提交充值申请
     */
    private fun submitRecharge(evt: VipRechargeSubmitEvt) {

        if (evt.transaction_id.isNullOrEmpty()) {
            Toast.makeText(this.context, "交易ID不能为空", Toast.LENGTH_SHORT).show()
            return
        }
        if (evt.num <= 0) {
            Toast.makeText(this.context, "交易数量不能为空", Toast.LENGTH_SHORT).show()
            return
        }
        if (evt.screenshot_key.isNullOrEmpty()) {
            Toast.makeText(this.context, "转账记录截图不能为空", Toast.LENGTH_SHORT).show()
            return
        }
        if (!rechargeDialog!!.isCharge()) {
            Toast.makeText(this.context, "请先确认已缴费", Toast.LENGTH_SHORT).show()
            return
        }
        presenter.rechargeSubmit(evt)

    }

    /**
     * 打开相册
     */
    private fun openSysGallery() {
        var galleryIntent = Intent(Intent.ACTION_PICK)  //跳转到 ACTION_IMAGE_CAPTURE
        galleryIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*")
        startActivityForResult(galleryIntent, CommonConstant.GALLERY_REQUEST_CODE)
    }

    /**
     * 选择相册响应
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == -1) {
            var imageUri = data!!.data
            var imageIs = this.activity!!.contentResolver.openInputStream(imageUri)
            var bitmap = BitmapFactory.decodeStream(imageIs)
            // 创建 RequestBody，用于封装构建RequestBody
            //压缩图片 reduceImage
            var file = reduceImage(bitmap)
            var requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file)
            // MultipartBody.Part  和后端约定好Key，这里的partName是用file
            var body = MultipartBody.Part.createFormData("screenshot", file.name, requestFile)

            presenter.vipUpload(body, 150)
        }

        super.onActivityResult(requestCode, resultCode, data)
    }

    /**
     * 压缩图片
     */
    fun reduceImage(bitmap: Bitmap): File {
        var file = File(this.context!!.externalCacheDir, "output_vip_image_temp.jpg")
        try {
            var quality = 100
            while (true) {
                var fileOutputStream = FileOutputStream(file)
                bitmap.compress(Bitmap.CompressFormat.JPEG, quality, fileOutputStream)
                quality -= 10
                var length = file.length()
                if (length < (1024 * 1024 * 1)) {
                    break
                }
            }
            return file
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return file
    }

    /**
     * 会员充值列表响应
     */
    override fun onRechargeSupportResp(response: VipRechargeResponse) {
        if (response.code == Constants.RESP_OK) {
            vipReChargeAdapter.update(response.data)
            var data = response.data
            if (data.size > 0) {
                presenter.loadRechargeCost(data[0].id)
                selVipRechargeInfo = data[0]
                vipReChargeAdapter.setExpandPosition(0)
            }
        }
    }

    /**
     * 计算费用响应
     */
    override fun onRechargeCostResp(response: CommonResponse<VipRechargeCostInfo>) {
        if (response.code == Constants.RESP_OK) {
            println(response)
            btnOpenRecharge.text = "确认缴费(需缴费\$${response.data.cost})"
        } else {
            Toast.makeText(context, response.msg, Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 上传图片响应
     */
    override fun onVipUploadResp(response: CommonResponse<JSONObject>) {
        if (response.code == Constants.RESP_OK) {
            vipUploadKey = response.data.getString("key")
//            Glide.with(this).load(response.data.getString("preview_url")).into(ivVipRecharge)
            rechargeDialog!!.setIvRecharge(response.data.getString("preview_url"))
        } else {
            Toast.makeText(context, response.msg, Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 提交审核响应
     */
    override fun onRechargeSubmitResp(response: CommonResponse<JSONObject>) {
        if (response.code == Constants.RESP_OK) {
            Toast.makeText(context, "提交成功,请等待审核", Toast.LENGTH_SHORT).show()
            if (rechargeDialog!!.isShowing) {
                rechargeDialog!!.dismiss()
            }
        } else {
            Toast.makeText(context, response.msg, Toast.LENGTH_SHORT).show()
        }
    }


    companion object {

        fun newInstance(): VipFragment {
            return VipFragment()
        }
    }

}